package com.application.util;

import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import com.application.controller.Code;
import com.application.domain.WXConstant;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;


import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class WechatUtil {
    private  static  String appid="wx1a2e690603ee4608";

    private static String secret="7bab890844da1452093d683e5327364f";

    private final static String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    RestTemplate restTemplate;
    public static JSONObject getSessionKeyOrOpenId(String code){

        String requestUrl="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> requestUrlParam = new HashMap<>();
        //小程序appId
        requestUrlParam.put("appid", WXConstant.appid);
        // 小程序secret  以上都是一些固定参数
        requestUrlParam.put("secret",WXConstant.secret);
        // 小程序返回的   code
        requestUrlParam.put("js_code",code);
        //默认参数
        requestUrlParam.put("grant_type","authorization_code");

        //  发送  post请求  读取调用 微信接口获取  openid用户唯一标识
        JSONObject jsonObject = JSONObject.parseObject(HttpClientUtil.doPost(requestUrl,requestUrlParam));
        Map<String, Object> innerMap = jsonObject.getInnerMap();


        innerMap.forEach((key,value) ->{
            System.out.println(key+":"+value);
        });

        return  jsonObject;
    }

    public   String getOpenid(String code){
        String url = WX_LOGIN_URL + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject=null;
        //  getForObject  一个用于更加简单的发送  Get方法的HTTP请求
        jsonObject = restTemplate.getForObject(url, JSONObject.class);
        System.out.println("here");
        Optional<JSONObject> optionalJSONObject = Optional.ofNullable(jsonObject);
        if(!optionalJSONObject.isPresent()){
            //获取openid失败
           return null;
        }
        var data = jsonObject.getInnerMap();
        /// assert data.get("openid") != null;
        /// return (String) data.get("openid");
        assert data.get("openid") != null;
        String openid= (String) data.get("openid");
        if(openid == null)
         return null;
        return openid;
    }


}
